<?php
define('_PSPEXEC_', '1');

if (!defined('APP_ROOT')) {
	exit('please define APP_ROOT in index.php that you application');
}

if (!defined('DS')) {
	define('DS', DIRECTORY_SEPARATOR);
}
if (!defined('TMP')) {
	define('TMP', APP_ROOT . DS . 'app' . DS . 'temp');
}
if (!defined('CONFIGS')) {
	define('CONFIGS', APP_ROOT . DS . 'app' . DS . 'config');
}

if (!defined('FRAMEWORK_ROOT')) {
	define('FRAMEWORK_ROOT', dirname(__FILE__));
}

if (!defined('PHP5')) {
	define('PHP5', (PHP_VERSION >= 5));
}
if (!defined('E_DEPRECATED')) {
	define('E_DEPRECATED', 8192);
}
error_reporting(E_ALL & ~E_DEPRECATED);
if (function_exists("memory_get_usage") && !defined("SYS_MEMORY_START")) {
	define("SYS_MEMORY_START", memory_get_usage());
}

define('SECOND', 1);
define('MINUTE', 60);
define('HOUR', 3600);
define('DAY', 86400);
define('WEEK', 604800);
define('MONTH', 2592000);
define('YEAR', 31536000);

require FRAMEWORK_ROOT . DS . 'Basics.php';
$TIME_START = getMicrotime();
define("SYS_TIME_START", $TIME_START);

require FRAMEWORK_ROOT . DS . 'lib' . DS . 'Object.php';
require FRAMEWORK_ROOT . DS . 'Param.php';
require APP_ROOT  . DS . 'app' . DS . 'config' . DS . 'params.php';
require FRAMEWORK_ROOT . DS . 'config' . DS . 'Params.php';
//ini_set("date.timezone","PRC");
date_default_timezone_set ("Asia/Shanghai");
require APP_ROOT  . DS . 'app' . DS . 'config' . DS . 'plugins.php';

require FRAMEWORK_ROOT . DS . 'lib' . DS .'router' . DS . 'Router.php';

require FRAMEWORK_ROOT . DS . 'lib' . DS .'network' . DS . 'Request.php';

Request::Instance();
require FRAMEWORK_ROOT . DS . 'Loader.php';
Loader::uses('pspframework.Basics');
Loader::uses('pspframework.Object');
Loader::uses('pspframework.Param');
Loader::uses('pspframework.router.Router');
Loader::uses('pspframework.network.Request');
Loader::uses('pspframework.Loader');
Loader::import('pspframework.utils.ClassRegistry');
Loader::import('pspframework.cache.Cache');
Loader::import('pspframework.datasource.Pop');	

class PSP extends Object{

	public static $RequestParams = array();

	public static $controller = null;	

	public static $IsPspdefaultController = false;	
	
	public static function run(){
        PSP::Instance(); 
		PSP::Start();
	}
	
	public static function Instance(){
	    self::$RequestParams = Request::$params;		
	}

	public static function Start(){
		self::cached('open');		
        $controller = & self::getController();		
		$controller->constructClasses();
		$controller->startupProcess();
		$methods = array_flip($controller->methods);
		if ( self::$IsPspdefaultController===false && !isset($methods[strtolower($controller->action)])) {
            exit('no action');
		}
		if(isset(Request::$query['iframeID']) && !empty(Request::$query['iframeID'])) {
		    $iframeID = Request::$query['iframeID'];
            $key = $controller->name.'_'.$controller->action.'_'.$iframeID;					
		    $sources = Cache::read($key, '_psp_tags_');
            if(!empty($sources)) {
				$controller->ViewFrame($sources,$iframeID,'',false);
            }			
		}
		if ( self::$IsPspdefaultController===false ) {
		    $output = call_user_func_array(array(&$controller, $controller->action), $controller->passedArgs);		
		}	
		if ($controller->autoRender) {
			$controller->output = $controller->render();
		} elseif (empty($controller->output)) {
			$controller->output = $output;
		}		
		$controller->shutdownProcess();		
		if (isset(Request::$query['return'])) {
			return $controller->output;
		}
		self::cached('write',$controller->output);
		echo($controller->output);	
	}	

	public static function & getController(){
	    $ctrlClass = self::$RequestParams['controller'];			
		self::$controller = & ClassRegistry::init(array('class' => $ctrlClass),'controllers');	
		if ( !self::$controller ) {
            Loader::import('controllers.pspdefault');		
		    self::$controller = new PspdefaultController();
			self::$IsPspdefaultController = true;
		}	
		self::$controller->here = Request::$here;
		self::$controller->webroot = Param::read('View.assetpath');
		
		self::$controller->params = Request::$params + Request::$query ;
        unset(self::$controller->params['passArgs']);
		self::$controller->base = Request::$base;		
		
		self::$controller->action = Request::$params['action'];
		
		self::$controller->subDir = Request::$params['controller'];		
		
		self::$controller->passedArgs = Request::$query['passArgs'] ;	

		if (!empty(Request::$data)) {
			self::$controller->data =& Request::$data;
		} else {
			self::$controller->data = null;
		}
		return self::$controller;
	}		

	public static function cached($type='open',$out=null) {
		if (Param::read('Cache.HtmlOpen') === true) {		 
			$filename = Request::$params['plugin'] . '_' .Request::$params['prefixes'] 
			. '_' . Request::$params['controller'] . '_' . Request::$params['action']. '_' . Request::$params['id'] . '.php';	
            $file = TMP  . DS . 'cache' . DS . 'views' . DS . $filename ;			
			if ( $type== 'open' ) {
                if( ! file_exists($file) ) {
                    exit("Not Found Html Cache File: " . $filename);
                }				
		        ob_start();
		        include ($file);
		        $out = ob_get_clean();		
		        if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
			        if (time() >= $match['1']) {
				        @unlink($file);
				        unset ($out);
				        return false;
			        } else {
				        $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->');
				        echo substr($out, $commentLength);
				        exit;
			        }
		        }							
				return $out;
			}else if ($type== 'write' && Param::read('Cache.HtmlWrite') === true && !file_exists($file) ) {
		        $now = time();
				$timestamp = Param::read('Cache.HtmlTime') ;
				if( empty($timestamp) ) $timestamp = MINUTE; 				
		        if (is_numeric($timestamp)) {
			        $cacheTime = $now + $timestamp;
		        } else {
			        $cacheTime = strtotime($timestamp, $now);
		        }			
			    if (!file_put_contents($file, '<!--cachetime:' . $cacheTime . '-->'.$out)) {
				    return false;
			    }				   
			}
		}
		return false;
	}	
		
}

?>